package com.apples.hexviewer2;

import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.MenuItem;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.apples.hexviewer2.adapter.RecentlyOpenRecyclerAdapter;
import com.apples.hexviewer2.databinding.ActivityThreeBinding;
import com.apples.hexviewer2.models.FileData;
import com.apples.hexviewer2.models.OnItemEventListener;
import com.apples.hexviewer2.utils.UIHelper;
import com.apples.hexviewer2.utils.io.FileHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 打卡文件的记录
 *
 * @author WangKaiFang
 * @date 2024/08/28
 */
public class ThreeActivity extends AppCompatActivity implements OnItemEventListener {

    private ActivityThreeBinding binding;
    public static final String RESULT_START_OFFSET = "startOffset";
    public static final String RESULT_END_OFFSET = "endOffset";
    private List<FileData> pathList;
    private RecentlyOpenRecyclerAdapter adapter;

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityThreeBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        initData();
    }

    private void initData() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayShowHomeEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
        setTitle(getString(R.string.action_recently_open_title));
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        String paths = preferences.getString("hex_viewer_recently_path", null);
        if (paths != null) {
            pathList = new ArrayList<>();
            String[] pathArr = paths.split("\\?\\|\\?");
            for (String s : pathArr) {
                pathList.add(new FileData(this, Uri.fromFile(new File(s))));
            }
            adapter = new RecentlyOpenRecyclerAdapter(this, pathList, this);
            binding.recyclerView.setAdapter(adapter);
            binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
            ItemTouchHelper itemTouchHelper = new ItemTouchHelper(adapter.getSwipeToDeleteCallback());
            itemTouchHelper.attachToRecyclerView(binding.recyclerView);
        }
    }

    /**
     * Called when the options item is clicked (home).
     *
     * @param item The selected menu.
     * @return boolean
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            setResult(RESULT_CANCELED);
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(@NonNull FileData ud) {
        if (ud.isNotFound()) {
            UIHelper.showErrorDialog(this, R.string.error_title,
                    String.format(getString(R.string.error_file_not_found),
                            FileHelper.getFileName(this, ud.getUri())));
            int position = pathList.indexOf(ud);
            pathList.remove(ud);
            adapter.notifyItemRemoved(position);
            onDelete(ud);
        } else {
            Intent i = new Intent(this, OneActivity.class);
            i.setData(ud.getUri());
            i.putExtra(RESULT_START_OFFSET, 0);
            i.putExtra(RESULT_END_OFFSET, 0);
            startActivity(i);
            finish();
        }
    }

    @Override
    public void onLongClick(@NonNull FileData ud) {
        new AlertDialog.Builder(this)
                .setCancelable(false)
                .setTitle(R.string.label_tip_msg16)
                .setMessage(ud.getUri().getPath())
                .setPositiveButton(android.R.string.ok, null)
                .show();
    }

    @Override
    public void onDelete(@NonNull FileData ud) {
        StringBuilder sbr = new StringBuilder();
        for (FileData data : pathList) {
            String s = data.getUri().getPath();
            sbr.append("?|?");
            sbr.append(s);
        }
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        if (sbr.length() > 0) {
            SharedPreferences.Editor edit = preferences.edit();
            edit.putString("hex_viewer_recently_path", sbr.substring("?|?".length()));
            edit.apply();
        } else {
            preferences.edit().remove("hex_viewer_recently_path").apply();
        }
    }

}